package com.gscitysfy.cus.drain.modules.inspection.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gscitysfy.cloudfrmwk.assistant.domain.Result;
import com.gscitysfy.cloudfrmwk.security.utils.SecurityUtils;
import com.gscitysfy.cus.drain.constants.DicConstant;
import com.gscitysfy.cus.drain.constants.RedisKeyConstant;
import com.gscitysfy.cus.drain.modules.inspection.entity.*;
import com.gscitysfy.cus.drain.modules.inspection.mapper.DrainInspectionMnJobMapper;
import com.gscitysfy.cus.drain.modules.inspection.mapper.DrainInspectionMnOrderMapper;
import com.gscitysfy.cus.drain.modules.inspection.mapper.DrainInspectionMnPlanMapper;
import com.gscitysfy.cus.drain.modules.inspection.service.IDrainInspectionMnPlanService;
import com.gscitysfy.cus.drain.modules.inspection.service.IDrainInspectionRlPointService;
import com.gscitysfy.cus.drain.modules.inspection.service.IDrainInspectionRlUserService;
import com.gscitysfy.cus.drain.modules.inspection.vo.DrainInspectionMnPlanExcel;
import com.gscitysfy.cus.drain.modules.inspection.vo.PlanVo;
import com.gscitysfy.cus.drain.utils.DateUtil;
import com.gscitysfy.cus.drain.utils.HttpResponseUtil;
import com.gscitysfy.cus.drain.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @since 2022-10-14 15:00:46
 */
@Service
@Slf4j
public class DrainInspectionMnPlanServiceImpl extends ServiceImpl<DrainInspectionMnPlanMapper, DrainInspectionMnPlan> implements IDrainInspectionMnPlanService {

    @Resource
    private DrainInspectionMnJobMapper jobMapper;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private IDrainInspectionRlUserService userService;

    @Resource
    private IDrainInspectionRlPointService pointService;

    @Resource
    private DrainInspectionMnOrderMapper orderMapper;

    /**
     * 新增或者修改巡检计划
     *
     * @param plan
     * @return
     */
    @Override
    public Result<Boolean> addOrUpdate(DrainInspectionMnPlan plan) {
        StringBuilder executor = new StringBuilder();
        plan.getUserList().forEach(user -> {
            executor.append(user.getCmUserName()).append(" ");
        });
        plan.setCmPlanExecutorName(executor.toString());

        boolean result;
        if (Objects.isNull(plan.getCmKid())) {
            //待审核
            plan.setCmPlanApprovalStatus(0);
            plan.setCmPlanNo(this.createPlanNo(plan.getCmPlanType()));
            result = this.save(plan);
        } else {
            //删除关联用户
            LambdaQueryWrapper<DrainInspectionRlUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DrainInspectionRlUser::getCmPlanId, plan.getCmKid());
            userService.remove(queryWrapper);

            //删除关联点位
            LambdaQueryWrapper<DrainInspectionRlPoint> pointQueryWrapper = new LambdaQueryWrapper<>();
            pointQueryWrapper.eq(DrainInspectionRlPoint::getCmPlanId, plan.getCmKid());
            pointService.remove(pointQueryWrapper);

            result = this.updateById(plan);
        }
        //更新执行人信息
        if (CollectionUtils.isNotEmpty(plan.getUserList())) {
            plan.getUserList().forEach(user ->
                    user.setCmPlanId(plan.getCmKid())
            );
            userService.saveBatch(plan.getUserList());
        }


        //更新区域点位信息
        if (CollectionUtils.isNotEmpty(plan.getAreaPoints())) {
            plan.getAreaPoints().forEach(point -> {
                point.setCmPlanId(plan.getCmKid());
                point.setCmPontType(0);
            });
            pointService.saveBatch(plan.getAreaPoints());
        }


        //更新巡检对象点位
        if (CollectionUtils.isNotEmpty(plan.getObjectPoints())) {
            plan.getObjectPoints().forEach(point -> {
                point.setCmPlanId(plan.getCmKid());
                point.setCmPontType(1);
            });
            pointService.saveBatch(plan.getObjectPoints());
        }

        return Result.content(result);
    }

    /**
     * 根据巡检类型创建巡检计划单编号
     *
     * @param type
     * @return
     */
    private String createPlanNo(String type) {
        String nextNo = null;
        if ("jhlx1".equals(type) || "jhlx3".equals(type)) {
            nextNo = "JHN" + DateUtil.formatDate(new Date(), DateUtil.yyyy_MM_dd_HH_mm);
        } else if ("jhlx2".equals(type) || "jhlx4".equals(type)) {
            nextNo = "JHW" + DateUtil.formatDate(new Date(), DateUtil.yyyy_MM_dd_HH_mm);
        }
        LambdaQueryWrapper<DrainInspectionMnPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(DrainInspectionMnPlan::getCmPlanNo, nextNo).orderByDesc(DrainInspectionMnPlan::getCmAddtime).last("limit 1");
        DrainInspectionMnPlan plan = this.getOne(queryWrapper);
        if (!Objects.isNull(plan)) {
            String preNo = plan.getCmPlanNo();
            String num = preNo.substring(preNo.length() - 3);
            String time = preNo.substring(0, preNo.length() - 3);
            DecimalFormat format = new DecimalFormat("000");
            //TODO 考虑超过999的情况
            nextNo = time + format.format(Integer.parseInt(num) + 1);
        } else {
            nextNo = nextNo + "001";
        }
        return nextNo;
    }

    /**
     * 逻辑删除巡检计划
     *
     * @param ids
     * @return
     */
    @Override
    public Result<Boolean> remove(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return Result.content(false);
        }
        List<Long> idList = Arrays.stream(ids.split(StrUtil.COMMA)).map(Long::parseLong).collect(Collectors.toList());
        LambdaUpdateWrapper<DrainInspectionMnPlan> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(DrainInspectionMnPlan::getCmUsable, true).in(DrainInspectionMnPlan::getCmKid, idList);

        return Result.content(this.update(updateWrapper));
    }

    /**
     * 获取巡检计划列表
     *
     * @param plan
     * @return
     */
    @Override
    public Result<Object> getPlanList(Page<DrainInspectionMnPlan> page, PlanVo plan) {
        LambdaQueryWrapper<DrainInspectionMnPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DrainInspectionMnPlan::getCmUsable, false);
        //计划依据
        if (StringUtils.isNotBlank(plan.getCmPlanBasis())) {
            queryWrapper.eq(DrainInspectionMnPlan::getCmPlanBasis, plan.getCmPlanBasis());
        }
        //计划类别
        if (StringUtils.isNotBlank(plan.getCmPlanType())) {
            queryWrapper.eq(DrainInspectionMnPlan::getCmPlanType, plan.getCmPlanType());
        }
        //计划频次
        if (StringUtils.isNotBlank(plan.getCmPlanFrequency())) {
            queryWrapper.eq(DrainInspectionMnPlan::getCmPlanFrequency, plan.getCmPlanFrequency());
        }
        //审核状态
        if (Objects.nonNull(plan.getCmPlanApprovalStatus())) {
            queryWrapper.eq(DrainInspectionMnPlan::getCmPlanApprovalStatus, plan.getCmPlanApprovalStatus());
        }
        //计划编号
        if (StringUtils.isNotBlank(plan.getCmPlanNo())) {
            queryWrapper.like(DrainInspectionMnPlan::getCmPlanNo, plan.getCmPlanNo());
        }
        //计划名称
        if (StringUtils.isNotBlank(plan.getCmPlanName())) {
            queryWrapper.like(DrainInspectionMnPlan::getCmPlanName, plan.getCmPlanName());
        }
        //计划开始时间范围查询
        if (Objects.nonNull(plan.getStartTime())) {
            queryWrapper.ge(DrainInspectionMnPlan::getCmPlanStartDate, plan.getStartTime());
        }
        if (Objects.nonNull(plan.getEndTime())) {
            queryWrapper.le(DrainInspectionMnPlan::getCmPlanStartDate, plan.getEndTime());
        }
        //计划负责人
        if (StringUtils.isNotBlank(plan.getCmPlanHeaderName())) {
            queryWrapper.like(DrainInspectionMnPlan::getCmPlanHeaderName, plan.getCmPlanHeaderName());
        }
        //计划执行人
        if (StringUtils.isNotBlank(plan.getCmPlanExecutorName())) {
            queryWrapper.like(DrainInspectionMnPlan::getCmPlanExecutorName, plan.getCmPlanExecutorName());
        }
        //计划对象类别
        if (StringUtils.isNotBlank(plan.getCmPlanObjectType())) {
            queryWrapper.eq(DrainInspectionMnPlan::getCmPlanObjectType, plan.getCmPlanObjectType());
        }
        //巡检计划是否完成
        if (Objects.nonNull(plan.getCmPlanIsCompleted())) {
            queryWrapper.eq(DrainInspectionMnPlan::getCmPlanIsCompleted, plan.getCmPlanIsCompleted());
        }
        //计划分类
        if (Objects.nonNull(plan.getCmPlanCategory())) {
            queryWrapper.eq(DrainInspectionMnPlan::getCmPlanCategory, plan.getCmPlanCategory());
        }
        queryWrapper.orderByDesc(DrainInspectionMnPlan::getCmAddtime);
        //是否分页返回
        if (Objects.isNull(plan.getIsPage()) || plan.getIsPage()) {
            Page<DrainInspectionMnPlan> planList = this.page(page, queryWrapper);

            planList.getRecords().forEach(item -> {
                LambdaQueryWrapper<DrainInspectionRlUser> userQueryWrapper = new LambdaQueryWrapper<>();
                userQueryWrapper.eq(DrainInspectionRlUser::getCmPlanId, item.getCmKid());
                List<DrainInspectionRlUser> userList = userService.list(userQueryWrapper);
                item.setUserList(userList);
            });
            return Result.content(planList);
        } else {
            //兼容数据导出,以勾选为准
            if (StringUtils.isNotBlank(plan.getIds())) {
                queryWrapper.clear();
                queryWrapper.in(DrainInspectionMnPlan::getCmKid, Arrays.stream(plan.getIds().split(StrUtil.COMMA)).map(Long::parseLong).collect(Collectors.toList()));
            }
            List<DrainInspectionMnPlan> planList = this.list(queryWrapper);

            return Result.content(planList);
        }
    }

    /**
     * 审核计划
     *
     * @param plan
     * @return
     */
    @Override
    public Result<Boolean> audit(PlanVo plan) {
        LambdaUpdateWrapper<DrainInspectionMnPlan> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(DrainInspectionMnPlan::getCmPlanApprovalStatus, plan.getCmPlanApprovalStatus())
                .set(DrainInspectionMnPlan::getCmPlanApprovalComments, plan.getCmPlanApprovalComments())
                .set(DrainInspectionMnPlan::getCmPlanApprovalUserId, SecurityUtils.getPrincipal().getUserId())
                .set(DrainInspectionMnPlan::getCmPlanApprovalUsername, SecurityUtils.getPrincipal().getName());

        //如果审核通过，设置第一次任我生成时间，提前三天生成巡检任务
        if (plan.getCmPlanApprovalStatus().equals(1)) {
            DrainInspectionMnPlan item = this.getById(plan.getCmKid());
            Calendar calendar = Calendar.getInstance();
            Date nextCreateDate;
            Date nextStartDate = null;
            //按天计
            if (item.getCmPlanFrequency().contains(DateUtil.DAY)) {
                nextStartDate = item.getCmPlanStartDate();
            }
            //按星期计
            if (item.getCmPlanFrequency().contains(DateUtil.WEEK)) {
                nextStartDate = DateUtil.getNextWeekMonday(item.getCmPlanStartDate());
            }
            //按月计
            if (item.getCmPlanFrequency().contains(DateUtil.MONTH) || item.getCmPlanFrequency().contains(DateUtil.SEASON)) {
                nextStartDate = DateUtil.getPerFirstDayOfMonth(item.getCmPlanStartDate());
            }
            //按年计
            if (item.getCmPlanFrequency().contains(DateUtil.YEAR)) {
                nextStartDate = DateUtil.getPerFirstDayOfYear(item.getCmPlanStartDate());
            }
            assert nextStartDate != null;

            calendar.setTime(nextStartDate);
            calendar.add(Calendar.DAY_OF_MONTH, -3);
            nextCreateDate = calendar.getTime();

            updateWrapper.set(DrainInspectionMnPlan::getCmPlanNextCreateDate, nextCreateDate);
            updateWrapper.set(DrainInspectionMnPlan::getCmPlanNextStartDate, nextStartDate);
        }

        updateWrapper.eq(DrainInspectionMnPlan::getCmKid, plan.getCmKid());
        return Result.content(this.update(updateWrapper));
    }


    /**
     * 导出巡检计划
     *
     * @param response
     * @param plan
     */
    @Override
    public void export(HttpServletResponse response, PlanVo plan) throws IOException {
        plan.setIsPage(false);
        List<DrainInspectionMnPlan> planList = (List<DrainInspectionMnPlan>) this.getPlanList(null, plan).getData();

        List<DrainInspectionMnPlanExcel> excelList = new ArrayList<>();

        Map<Object, Object> planBasis = redisUtil.hmget(RedisKeyConstant.DATA_DICT_KEY + DicConstant.PLAN_BASIS);
        Map<Object, Object> planType = redisUtil.hmget(RedisKeyConstant.DATA_DICT_KEY + DicConstant.PLAN_TYPE);
        Map<Object, Object> planObjectType = redisUtil.hmget(RedisKeyConstant.DATA_DICT_KEY + DicConstant.PLAN_OBJECT_TYPE);
        Map<Object, Object> planFrequency = redisUtil.hmget(RedisKeyConstant.DATA_DICT_KEY + DicConstant.PLAN_FREQUENCY);

        planList.forEach(item -> {
            DrainInspectionMnPlanExcel excel = new DrainInspectionMnPlanExcel();
            BeanUtils.copyProperties(item, excel);

            excel.setCmPlanBasis(planBasis.get(item.getCmPlanBasis()).toString());
            excel.setCmPlanType(planType.get(item.getCmPlanType()).toString());
            excel.setCmPlanObjectType(planObjectType.get(item.getCmPlanObjectType()).toString());
            excel.setCmPlanFrequency(planFrequency.get(item.getCmPlanFrequency()).toString());
            excelList.add(excel);
        });

        String fileName = "巡检计划记录.xlsx";
        HttpResponseUtil.setResponseHeaders(response, fileName);
        EasyExcel.write(response.getOutputStream(), DrainInspectionMnPlanExcel.class)
                .sheet("巡检计划")
                .doWrite(() -> excelList);
    }

    /**
     * 巡检计划详情
     * @param id
     * @return
     */
    @Override
    public Result<DrainInspectionMnPlan> viewById(Long id) {
        DrainInspectionMnPlan plan = this.getById(id);
        //巡检用户
        LambdaQueryWrapper<DrainInspectionRlUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DrainInspectionRlUser::getCmPlanId, id);
        List<DrainInspectionRlUser> userList = userService.list(queryWrapper);
        plan.setUserList(userList);
        //巡检区域
        LambdaQueryWrapper<DrainInspectionRlPoint> pointQueryWrapper = new LambdaQueryWrapper<>();
        pointQueryWrapper.eq(DrainInspectionRlPoint::getCmPlanId, id).eq(DrainInspectionRlPoint::getCmPontType, 0);
        plan.setAreaPoints(pointService.list(pointQueryWrapper));
        //巡检对象
        pointQueryWrapper.clear();
        pointQueryWrapper.eq(DrainInspectionRlPoint::getCmPlanId, id).eq(DrainInspectionRlPoint::getCmPontType, 1);
        plan.setObjectPoints(pointService.list(pointQueryWrapper));

        return Result.content(plan);
    }


    /**
     * 创建巡检任务
     */
    @Override
    public void createJob() {
        //获取所有未删除的、审核通过的、未结束的巡检计划
        LambdaQueryWrapper<DrainInspectionMnPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DrainInspectionMnPlan::getCmUsable, false).
                eq(DrainInspectionMnPlan::getCmPlanApprovalStatus, 1).eq(DrainInspectionMnPlan::getCmPlanIsCompleted, 0)
                .and(wrapper->wrapper.eq(DrainInspectionMnPlan::getCmPlanCategory, 0).or().eq(DrainInspectionMnPlan::getCmPlanCategory, 2));

        List<DrainInspectionMnPlan> plans = this.list(queryWrapper);

        Integer now = DateUtil.DateToInt(new Date());
        int num = 1;

        DecimalFormat format = new DecimalFormat("000");
        String jobNo = "XJRW" + DateUtil.formatDate(new Date(), DateUtil.yyyy_MM_dd_HH_mm);
        for (DrainInspectionMnPlan plan : plans) {
            //下一次任务开始时间大于计划结束时间，则设置计划已完成
            if (DateUtil.DateToInt(plan.getCmPlanNextStartDate()) >= DateUtil.DateToInt(plan.getCmPlanEndDate())) {
                plan.setCmPlanIsCompleted(1);
                this.updateById(plan);
            } else if (Objects.nonNull(plan.getCmPlanNextCreateDate()) && now >= DateUtil.DateToInt(plan.getCmPlanNextCreateDate())) {
                DrainInspectionMnJob job = new DrainInspectionMnJob();
                BeanUtils.copyProperties(plan, job);
                job.setCmKid(null);
                job.setCmPlanId(plan.getCmKid());
                job.setCmPlanCategory(plan.getCmPlanCategory());
                job.setCmJobNo(jobNo + format.format(num));
                num++;

                job.setCmAddtime(null);
                job.setCmUptime(null);
                //待巡检
                job.setCmJobStatus(1);
                //任务计划开始时间、计划结束时间
                job.setCmJobStartDate(plan.getCmPlanNextStartDate());
                //设置计划结束时间
                this.setPlanEndDate(plan, job);

                jobMapper.insert(job);
                //更新巡检计划
                this.updateById(plan);
            }
        }
    }

    /**
     * 计算任务结束日期
     * @param job
     */
    private void setPlanEndDate(DrainInspectionMnPlan plan, DrainInspectionMnJob job) {
        Date startDate = job.getCmJobStartDate();
        //巡检周期
        String period = plan.getCmPlanFrequency();
        String num = period.substring(0, 1);
        String cycle = period.substring(1);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);

        if (DateUtil.DAY.equals(cycle)) {
            calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(num));
        }
        if (DateUtil.WEEK.equals(cycle)) {
            calendar.add(Calendar.WEEK_OF_YEAR, Integer.parseInt(num));
        }
        if (DateUtil.MONTH.equals(cycle)) {
            calendar.add(Calendar.MONTH, Integer.parseInt(num));
        }
        if (DateUtil.SEASON.equals(cycle)) {
            calendar.add(Calendar.MONTH, Integer.parseInt(num) * 3);
        }
        if (DateUtil.YEAR.equals(cycle)) {
            calendar.add(Calendar.YEAR, Integer.parseInt(num));
        }
        //任务结束时间大于整体计划结束时间，以计划结束时间为准
        if (DateUtil.DateToInt(calendar.getTime()) >= DateUtil.DateToInt(plan.getCmPlanEndDate())) {
            job.setCmJobEndDate(plan.getCmPlanEndDate());
            //整体计划结束
            plan.setCmPlanIsCompleted(1);
        } else {
            job.setCmJobEndDate(calendar.getTime());
            //设置下次生成任务时间， 下次任务开始时间
            plan.setCmPlanNextStartDate(calendar.getTime());
            calendar.add(Calendar.DAY_OF_MONTH, -3);
            plan.setCmPlanNextCreateDate(calendar.getTime());
        }
    }


    /**
     * 创建维护单
     */
    @Override
    public void createOrder() {
        //获取所有未删除的、审核通过的、未结束的巡养计划
        LambdaQueryWrapper<DrainInspectionMnPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DrainInspectionMnPlan::getCmUsable, false).
                eq(DrainInspectionMnPlan::getCmPlanApprovalStatus, 1).eq(DrainInspectionMnPlan::getCmPlanIsCompleted, 0)
                .eq(DrainInspectionMnPlan::getCmPlanCategory, 1);

        List<DrainInspectionMnPlan> plans = this.list(queryWrapper);

        Integer now = DateUtil.DateToInt(new Date());
        int num = 1;

        DecimalFormat format = new DecimalFormat("000");
        String orderNo = "WYRW" + DateUtil.formatDate(new Date(), DateUtil.yyyy_MM_dd_HH_mm);
        for (DrainInspectionMnPlan plan : plans) {
            //下一次任务开始时间大于计划结束时间，则设置计划已完成
            if (DateUtil.DateToInt(plan.getCmPlanNextStartDate()) >= DateUtil.DateToInt(plan.getCmPlanEndDate())) {
                plan.setCmPlanIsCompleted(1);
                this.updateById(plan);
            } else if (Objects.nonNull(plan.getCmPlanNextCreateDate()) && now >= DateUtil.DateToInt(plan.getCmPlanNextCreateDate())) {
                DrainInspectionMnOrder order = new DrainInspectionMnOrder();
                this.copyPlanProperties(plan, order);

                order.setCmOrderNo(orderNo + format.format(num));
                num++;

                order.setCmOrderStartTime(plan.getCmPlanNextStartDate());
                this.setOrderEndDate(plan, order);

                // 任务来源（0养护任务-计划生成的  1pc端问题,巡查上报问题生成的  2小程序直接问题上报的）
                order.setSourceType("0");
                //是否是维养任务  （0表示否 根据问题创建的 1表示是 根据计划创建的）
                order.setIsOrder("1");
                orderMapper.insert(order);
                //更新巡检计划
                this.updateById(plan);
            }
        }
    }

    /**
     * copy计划字段
     * @param plan
     * @param order
     */
    private void copyPlanProperties(DrainInspectionMnPlan plan, DrainInspectionMnOrder order){
        //计划id
        order.setCmPlanId(plan.getCmKid());
        //类型：维养任务生成
        order.setSourceType("1");
        order.setCmOrderHeaderId(plan.getCmPlanHeaderId());
        order.setCmOrderHeaderName(plan.getCmPlanHeaderName());
        order.setCmOrderHeaderPhone(plan.getCmPlanHeaderPhone());

        LambdaQueryWrapper<DrainInspectionRlUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DrainInspectionRlUser::getCmPlanId, plan.getCmKid());
        List<DrainInspectionRlUser> userList = userService.list(queryWrapper);
        if(!userList.isEmpty()){
            order.setCmOrderExecutorId(userList.get(0).getCmUserId());
            order.setCmOrderExecutorName(userList.get(0).getCmUserName());
        }
        //待处置
        order.setCmOrderStatus(0L);
    }


    /**
     * 算任务结束日期
     * @param plan
     * @param order
     */
    private void setOrderEndDate(DrainInspectionMnPlan plan, DrainInspectionMnOrder order) {
        Date startDate = order.getCmOrderStartTime();
        //巡检周期
        String period = plan.getCmPlanFrequency();
        String num = period.substring(0, 1);
        String cycle = period.substring(1);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);

        if (DateUtil.DAY.equals(cycle)) {
            calendar.add(Calendar.DAY_OF_MONTH, Integer.parseInt(num));
        }
        if (DateUtil.WEEK.equals(cycle)) {
            calendar.add(Calendar.WEEK_OF_YEAR, Integer.parseInt(num));
        }
        if (DateUtil.MONTH.equals(cycle)) {
            calendar.add(Calendar.MONTH, Integer.parseInt(num));
        }
        if (DateUtil.SEASON.equals(cycle)) {
            calendar.add(Calendar.MONTH, Integer.parseInt(num) * 3);
        }
        if (DateUtil.YEAR.equals(cycle)) {
            calendar.add(Calendar.YEAR, Integer.parseInt(num));
        }
        //任务结束时间大于整体计划结束时间，以计划结束时间为准
        if (DateUtil.DateToInt(calendar.getTime()) >= DateUtil.DateToInt(plan.getCmPlanEndDate())) {
            order.setCmOrderEndTime(plan.getCmPlanEndDate());
            //整体计划结束
            plan.setCmPlanIsCompleted(1);
        } else {
            order.setCmOrderEndTime(calendar.getTime());
            //设置下次生成任务时间， 下次任务开始时间
            plan.setCmPlanNextStartDate(calendar.getTime());
            calendar.add(Calendar.DAY_OF_MONTH, -3);
            plan.setCmPlanNextCreateDate(calendar.getTime());
        }
    }


}
